import ast

from sqlalchemy import Column, Integer, String, ForeignKey, orm
from sqlalchemy.orm import relationship, backref
from flask import jsonify
from app.libs.job import execute_job
from app.libs.ls_apschedule import APScheduler
from app.models.base import db
from app.models.base import Base
from app.models.case_group import CaseGroupModel


class JobModel(Base):
    """
    用单例
    """
    __tablename__ = 'job'
    id = Column(Integer, primary_key=True)
    space_id = Column(Integer, nullable=False)
    group_id = Column(Integer, nullable=False)

    @orm.reconstructor
    def __init__(self):
        super(JobModel, self).__init__()
        self.fileds = ['id', 'space_id', 'group_id']

    def new_jod(self, group_id):
        case_group = CaseGroupModel().query.filter_by(id=group_id).first_or_404()
        try:
            self.query.filter_by(group_id=group_id).first_or_404()
        except:
            # 添加值数据库
            self.add_job(case_group.space_id, group_id)
        APScheduler().add_job(func=execute_job, jobid=group_id, kwargs=case_group, args=({group_id: group_id}))
        case_group.update_execute_status(group_id, True)

    @staticmethod
    def add_job(space_id, group_id):
        with db.auto_commit():
            job = JobModel()
            job.space_id = space_id
            job.group_id = group_id
            db.session.add(job)

    @staticmethod
    def pause_job(group_id):
        APScheduler.pause_job(group_id)
        CaseGroupModel().update_execute_status(group_id, False)
